Reputation:
Basically I am a beginner to Angular as well as java script. Here am trying to validate a Reactive form Text field with some conditions.
Conditions are:
Asterisk() is allowed to give as input from 5th to 13th position , and everything else is considered as invalid after Asterisk(). Eg: 8500*001001… (Invalid) 8500* (valid)
I am aware to write simple custom validations. If any one having idea please help me out or you can suggest me as well. Thanks in Advance.
Upvotes: 3
Views: 1257
Reputation: 24424
There are may way if you know the regex pattern you can use Validators.pattern
I recommend writing a custom validator will be easier to maintain and more readable than complex regex pattern , and you can provide custom error message about validation of the value , another thing custom validator is just a function that return an object if the validation is failed or null if the validation succeed.
custom reactive form validator
import { AbstractControl, ValidationErrors } from "@angular/forms"
export const inputTextValidator = function inputTextValidator(control: AbstractControl): ValidationErrors | null {
let getErrorObject = function (message): ValidationErrors {
return {
inputText: true,
message // provide custom error message related to the validation role
}
}
let value: string = control.value || '';
// check if value length between specific range like 7-25
if (value.length < 7 && value.length < 25) {
return getErrorObject(`text length must be between 7-25 ,current length ${value.length}`);
}
// check if value invalid characters like #$%^%$^/-+
let validCharacters = /^[a-zA-Z0-9\*]+$/g
if (validCharacters.test(value) === false) {
return getErrorObject(`text has invalid characters,current value ${value.length}`);
}
let asterisk = /^\w+\*?$/g
if (asterisk.test(value) === false) {
return getErrorObject(`only one asterisk at the end of the string is valid,current value ${value.length}`);
}
// check the asterisk postion at 8th-13th
let indexOfAsterisk: number = value.indexOf('*'); // index base on 0
if (indexOfAsterisk >= 0 && (indexOfAsterisk < 8 || indexOfAsterisk > 12)) {
return getErrorObject(`asterisk must bee in postion at 8 -13 th,current * postion ${indexOfAsterisk}`);
}
return null;
}
Not in your example you show is the valid position for asterisk start from 5th and this will break the first role about the min length of the value that why I make sure the min is 8 at latest
Upvotes: 0