I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.
There's a lot of verbosity in here, and I'm deeply against it, so, my conclusive answer would be:
/^\w+$/
\w
is equivalent to [A-Za-z0-9_]
, which is pretty much what you want. (unless we introduce unicode to the mix)
Using the +
quantifier you'll match one or more characters. If you want to accept an empty string too, use *
instead.
In Computer Science, an Alphanumeric value often means the first character is not a number but is an alphabet or underscore. Thereafter the character can be 0-9
, A-Z
, a-z
, or underscore (_
).
Here is how you would do that:
Tested under php:
$regex = '/^[A-Za-z_][A-Za-z\d_]*$/'
or take this
^[A-Za-z_][A-Za-z\d_]*$
and place it in your development language.
Here is the regex for what you want with a quantifier to specify at least 1 character and no more than 255 characters
[^a-zA-Z0-9 _]{1,255}
Required Format Allow these 3:
Don't Allow other formats:
validatePnrAndTicketNumber(){
let alphaNumericRegex=/^[a-zA-Z0-9]*$/;
let numericRegex=/^[0-9]*$/;
let numericdashRegex=/^(([1-9]{3})\-?([0-9]{10}))$/;
this.currBookingRefValue = this.requestForm.controls["bookingReference"].value;
if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){
this.requestForm.controls["bookingReference"].setErrors({'pattern': false});
}else{
this.requestForm.controls["bookingReference"].setErrors({'pattern': true});
}
}
<input name="booking_reference" type="text" [class.input-not-empty]="bookingRef.value"
class="glyph-input form-control floating-label-input" id="bookings_bookingReference"
value="" maxlength="14" aria-required="true" role="textbox" #bookingRef
formControlName="bookingReference" (focus)="resetMessageField()" (blur)="validatePnrAndTicketNumber()"/>
^\w*$
will work for below combinations
1
123
1av
pRo
av1
For me there was an issue in that I want to distinguish between alpha, numeric and alpha numeric, so to ensure an alphanumeric string contains at least one alpha and at least one numeric, I used :
^([a-zA-Z_]{1,}\d{1,})+|(\d{1,}[a-zA-Z_]{1,})+$