0
votes

I'm using Angular Reactive form in my Angular app and i have a <select> input where the default value if -1, by setting Validators.required even if the value is still -1 it will be accepted, so how could i make a validator to accept the value if is valid and is != -1?

I was trying to do something like this but it's not working:

coperti: new FormControl(-1, [Validators.required, Validators.pattern(`[\d]`)]),
1

1 Answers

2
votes

You can create a custom validator:

form = new FormGroup({
    coperti: new FormControl("", [
      (c) => {
        // Here the c is your form control and we check if the  value is -1 or 0
        if (c.value === -1 || c.value === 0) {
        // if the condition is met we return the error
          return { wrong: true };
        }
        // if the condition isn't met (e.g. the form is valid) we return null, which
        // will not apply errors on the form control
        return null;
      }
    ])
  });

All validators are simple functions so feel free to create whatever custom validator when needed, don't limit yourself only to the build in ones.