I am working on Angular 5 Reactive Form validation and trying to validate UK PostCode using custom validation function which is working and testing apart from in case provide extra letter or numeric value at end of postcode 2nd part, it validate true, for example NW10 5NW is correct but if I type anything like NW10 5NWRRRRRRRRRRRRRRRR is also return true which is not correct.
I have tried following regular experssion on https://regexr.com/ and it return correct response, not sure why in javaScript not behaving same way???
function postCodeValidator(control: FormControl)
{
let givenPostCode = control.value;
let UKPostCodePattern = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})/;
var isUKPostCodeValid = UKPostCodePattern.test(givenPostCode);
console.log("postcode validity ",isUKPostCodeValid, " for ", givenPostCode);
if(!isUKPostCodeValid)
{
return {
postCode:{
required:"UK Valid PostCode",
provided: givenPostCode
}
}
}
return null;
}
Try using following regex
^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2}))$
https://regexr.com/3pp3r
Related
I am trying to implement a search using regex . To validate if the entered value is a valid regex in the search box I am using the source code from a library regex-validate (REGEX VALIDATION LIBRARY - regex-regex)
If the entered value is a valid regex then I am Parsing it to a regular expression using the source code from this library Regex-Parse) (PARSING LIBRARY - Regex Parser) to filter/search using the parsed regex.Here is a code snippet for the same
import { useState } from "react";
import "./styles.css";
import { re, RegexParser } from "./regexValidation";
export default function App() {
const [val, setVal] = useState("");
const [validRegex, setValidRegex] = useState(false);
const validateRegex = (val: string) => {
setVal(val);
if (val === "") {
setValidRegex(false);
return;
}
// to check if the entered value(val) is a valied regex in string
if (re.test(val)) {
setValidRegex(false);
// parsing the entered value(val) to a regularexpression
const convertToRegex = RegexParser(val);
//filtering logic to filter based on convertToRegex variable
} else {
setValidRegex(true);
}
};
const handleChange = (e: any) => {
validateRegex(e.target.value);
};
return (
<div className="App">
<input value={val} onChange={handleChange}></input>
<h1>{validRegex ? "inValidRegex" : "ValidRegex"}</h1>
</div>
);
}
CodeSandBox link for the regex search RegexValidationSearch
I am facing an issue when the user enters '/?/' or '/*/' the re.test(val) returns true thereby implying that it is a valid regex but when it is trying to get parsed that is this line of code const convertToRegex = RegexParser(val) it throws the following errorRegexError
Is there any way to fix this such that this line of code re.test(val) returns false when the user enters any invalid regular expression there by implying that it is an invalid regex(in string format) and hence there is no need to parse it to a regular expression
This looks like it might be an incompatibility between the two libraries you are using (ie, they have different ideas of what valid Regex is).
Easiest way to fix this (and honestly the safest too, since you're dealing with user input) is to wrap your entire parsing logic with a try/catch like this:
// to check if the entered value(val) is a valied regex in string
if (re.test(val)) {
let convertToRegex;
try {
convertToRegex = RegexParser(val);
setValidRegex(true); // only set this AFTER a successful parse.
// also note I've swapped the true / false value here.
} catch (e) {
setValidRegex(false);
}
if (convertToRegex) {
// TODO: implement filtering logic based on convertToRegex variable
}
} else {
// NOTE: it didn't parse correctly, shouldn't this be false?
setValidRegex(false); // I've changed it for you
}
Also I think(?) you've made a couple errors in how you're handling setValidRegex which I've corrected in code. Don't be optimistic and say the user input is valid regex when you haven't actually confirmed (by creating a RegexParser) that it is!
With this approach there's an argument for deleting the re.test(val) and the other library entirely since you can get what you want by simply try/catch-ing. Up to you to decide if this is a decent choice for your codebase.
I want user can enter his email id in English language only, User can't enter Japanese or chinese even if he has an option in his keyboard.
I searched but I found some post which restrict user to enter special characters.
only allow English characters and numbers for text input
I have written this code.
_handleChange = (name, value) => {
value = value.replace(/[^A-Za-z]/ig, '');
const { data } = this.state;
data[name] = value;
this.setState(
{
data: JSON.parse(JSON.stringify(data))
},
() => {
this._isValid(name)
}
);
};
Please suggest.
Thank you.
In Javascript code of the _handleChange function you can add following regex inside a conditional block while calling setState:
if(/\w[\w|.|-|+]+#[\w|-]+.[\w]{2,}/.test(emaiId))
this.setState({emailId})
RegExp.prototype.test() will check the provided string against the regex and return boolean value.
I'm working on validating multiple emails from an input field and can't really get my Regex to work. I have an input field that has emails separated by a comma, semi-colon, space and sometimes no space, something like this:
user1#email.comuser2#gmail.com , user3#email.com;user4#gmail.com user5#email.com
I'm trying to get all emails using Regex and then validate each of them, but not really sure how to do it using Regex in Javascript.
I have written my code in Java and it works great at getting all emails:
Java code:
String employeeEmails = "user1#email.com , user2#gmail.com user3#email.com;user4#gmail.com";
Matcher eachEmail = Pattern.compile("\\w+#\\w+.com").matcher(employeeEmails);
List<String> emailList = new ArrayList<String>();
while (eachEmail.find()){
emailList.add(eachEmail.group());
}
Finally emailList has all the emails
Now I'm trying to get all emails in Javascript and validate each of them and if one of them is not a valid email throw an error. Here's my code:
Javascript:
var regex1 = /\w+#\w+.com/; // This will get all emails from inputField
var emailList = regex1;
var regex2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/; // This will validate each email
for(var i = 0;i < emailList.length;i++) {
if(!regex2.test(emailList[i])) {
return me.invalidText; // throw error if an email is not valid
}
}
Need to get this done in Javascript. Can anyone tell me what I'm missing please? Thank you in advance!
I hope this help you:
employeeEmails = "user1#email.com , user2#gmail.com user3#email.com;user4#gmail.com*john#doe";
function extractEmails(x) { return x.match(/([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4})/g); }
var emails=extractEmails(employeeEmails);
// The emails already in an array, now a more exhaustive checking:
function validateEmail(v) { var regex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(v);
}
emails.forEach(function(email, index)
{
// Here you can handle each employee emails.
//
// Example:
var verified=validateEmail(email);
document.write(' validation is '+ verified +' for '+ email +'<br>');
});
Sources:
How to validate email address in JavaScript?
https://www.w3schools.com/js/
Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}
I am trying to write a function in Javascript to validate email address. Here is the function.
function validateEmailAddress() {
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/;
var regexPatternForEmail = new RegExp(patternForEmail, 'i');
// Email address and the Confirm Email address values should match
if ($('#txtEmail').val() != $('#txtConfirmEmail').val()) {
$('#dvErrorMsg').html("Email addresses do not match.");
$('#txtEmail').focus();
return false;
}
else if (!regexPatternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
else
return true;
}
The problem here is I am getting an error, 'Syntax error in regular expression' during RegExp object instantiation.
I tried debuggin in IE 11 and that's where i found the error.
Could someone please suggest me a solution for this.
Screen shot taken while debugging:
You don't need to create another regex variable using RegExp constructor. Just use only the below.
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
i at the last called case-insensitive modifier which helps to do a case-insensitive match.
Example:
> var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
> patternForEmail.test('foo#bar.com')
true
> patternForEmail.test('#foo#bar.com')
false
In most of the times this kinds of errors occurs because of browser compatibility , so always we need to use the codes which can be run in all the browsers. I hope the following changes will help you.
var patternForEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
then you can match the expression using
if (patternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
or else you can use match() function also which will be more flexible for all the browsers.
var email = $('#txtEmail').val();
if (!email.match(/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i)) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}