Reputation: 434
I am trying to validate input data while entered the data. Where, I want to validate Input data in digit and Data Format is: 000-000-000. Where, also I have to validate each 000 value range in between (000-255) only.
Like: 000-000-000 to 255-255-255.
onHandleValidation = (event, submitted) =>
{
let fields = this.state.formFields;
let errors = this.state.formErrors;
let field = (event)? event.target.name: "";
let Validate = true;
if (field === 'digit' || submitted) {
if(fields.digit=== ""){
errors["digit"] = "This field is required";
Validate = false;
} else {
if(/^\d{3}-\d{3}-\d{3}$/.test(fields.digit) === false){
errors['digit'] = "digit Format 000-000-0000 Required";
Validate = false;
}
}
}
this.setState({formErrors: errors, formValid: formValid});
return Validate;
}
Validation for Format: 000-000-000 is done. For second Validation, I am trying, but, Not find any solution yet.
For Any Help. Thank You!
Upvotes: 0
Views: 130
Reputation: 20737
This would be how to do it in pure regex
^(?:[0-1]\d\d|2[0-4]\d|25[0-5])-(?:[0-1]\d\d|2[0-4]\d|25[0-5])-(?:[0-1]\d\d|2[0-4]\d|25[0-5])$
https://regex101.com/r/QzpxmF/1/
Upvotes: 1
Reputation: 1547
Just a basic idea of how to do this
const valid = "000-000-000";
const valid2 = "255-255-255";
const valid3 = "123-200-067";
const invalid1 = "000-000-0001";
const invalid2 = "000-0001";
const invalid3 = "000-000-300";
const validate = (digits) => {
const allDigits = digits.split("-");
console.log(allDigits);
// return false if not enough parts
if (allDigits.length !== 3) {
console.log("not enough parts");
return false;
}
// validate length of parts
const validLengths = allDigits.every((digit) => digit.length === 3);
// return false if one length is violated
if (!validLengths) {
console.log("at least one part has an incorrect length");
return false;
}
// validate maximum and minimum
const inRange = allDigits.every((digit) => digit >= 0 && digit <= 256);
if (!inRange) {
console.log("at least one is out of range");
return false;
}
return true;
};
console.log("validate", valid, validate(valid));
console.log("validate", valid2, validate(valid2));
console.log("validate", valid3, validate(valid3));
console.log("validate", invalid1, validate(invalid1));
console.log("validate", invalid2, validate(invalid2));
console.log("validate", invalid3, validate(invalid3));
I am not the regex guru, so someone else might add a regex solution
Upvotes: 1