How to Get the Raw Value an ≪Input Type="Number"≫ Field

How to get the raw value an input type=number field?

According to the WHATWG, you shouldn't be able to get the value unless it's valid numeric input. The input number field's sanitization algorithm says the browser is supposed to set the value to an empty string if the input isn't a valid floating point number.

The value sanitization algorithm is as follows: If the value of the
element is not a valid floating-point number, then set it to the empty
string instead.

By specifying the type (<input type="number">) you're asking the browser to do some work for you. If, on the other hand, you'd like to be able to capture the non-numeric input and do something with it, you'd have to rely on the old tried and true text input field and parse the content yourself.

The W3 also has the same specs and adds:

User agents must not allow the user to set the value to a non-empty
string that is not a valid floating-point number.

Get raw value from invalid input field

Here is what i came up with for your scenario.

Basically you can write a directive which requires ngModel (ngModelController). The ngModelController has a array of parsers which it call to parse the view value in a pipeline manner. If validation fail these parsers do not update the model. If you inject a custom parser at the start of this parsers array, you can get the each view change value and do anything you want with it.

See my plunkr here http://plnkr.co/edit/ruB42xHWj7dBxe885OGy?p=preview (See console)

The basic code would be

ngModelCtrl.$parsers.splice(0,0,(function (viewValue) {
console.log("The view value is:"+viewValue)
return viewValue;
}));

Also see ngModelController documenation

Reactjs Form Validations-for input type number the text field in constantly showing single value even after giving backspace from the keyboard

You are not completely handling the input value. Since you apply the check that if value === '', then just set the error. Just console the value in errorHandle function, you will see you will get the empty string, but since you are not setting the '' in state, it input value is not updated and remains the last value. You can do this:

const errorHandle = (name, value) => {
setdocId(value);
const errors = {};
if (name === 'docID') {
if (value === '') {
// Set the error
} else {
setdocId(value);
}
}
};

Don't add check for empty value. Just update the state. You can check if value is empty then set the error.

HTML - I cannot copy the value from a read-only input type

You need to set the value of that input-field instead of the placeholder:

<input type="text" value="{some variable}" class="form-control" readonly>


Related Topics



Leave a reply



Submit