Reputation: 77
I have the below code in HTML5 for validating some names
<input name="desiredNames" type="text" placeholder="your-site-name" pattern="[a-z0-9\-\.]{3,25}" id="desiredNames">
It works, but I want to add to it an extra checking feature using regex, as follow: 1. the name is not allowed to start with sign period . or sign minus - 2.the name is not allowed to end with sign period . or sign minus -
I don't know how to use ^, $, ? to make these happened. ( I tried a few examples seen in the forums) Also to that html code I have the below js code
(function checkName() {
let wantedNames = document.getElementById('desiredNames');
let form = document.getElementById('form');
let elem = document.createElement('div');
elem.id = 'notify';
elem.style.display = 'none';
form.appendChild(elem);
wantedNames.addEventListener('invalid', function(event){
event.preventDefault();
if ( ! event.target.validity.valid ) {
wantedNames.className = 'invalid animated shake';
elem.textContent = 'Name can contains small letters, numbers, dot . and minus -,but not at the beginning or at the end, ie escu.ionel-74';
elem.className = 'error';
elem.style.display = 'block';
}
});
wantedNames.addEventListener('input', function(event){
if ( 'block' === elem.style.display ) {
wantedNames.className = '';
elem.style.display = 'none';
}
});
})();
Any tips and some good resources for regex patterns?
Thx
Upvotes: 1
Views: 80
Reputation: 626758
There are a lot of ways to achieve that, but the shortest would be to add \b
word boundaries on both ends to require word chars at the start and end of the input. Note you do not need to use ^
(start of string) and $
(end of string) anchors, because they are added automatically by the HTML5 engine when compiling the regex from the pattern.
So, you may use
pattern="\b[a-z0-9.-]{3,25}\b"
and it will be parsed as /^(?:\b[a-z0-9.-]{3,25}\b)$/
matching 3 to 25 lowercase ASCII letters (add A-Z
after [
to also match uppercase ASCII letters), digits, .
or -
, but no .
or -
will be allowed at the start and end of the string.
See the demo:
input:valid {
color: black;
}
input:invalid {
color: red;
}
<input name="desiredNames" type="text" placeholder="your-site-name" pattern="\b[a-z0-9.-]{3,25}\b" id="desiredNames" />
Upvotes: 2
Reputation: 129
You will try below option.
" <input required pattern="[A-Za-z0-9]+[\.\-]*[A-Za-z0-9]+" maxlength=25 minlength=3 name="desiredNames" type="text" placeholder="your-site-name" id="desiredNames" > "
it's working for me.
Upvotes: 0
Reputation: 12649
You're probably looking for this:
^[^.-].{1,23}[^.-]$
^
means starting at the beginning of string, except when inside []
which means not
.
means any character except newline, but inside []
means period
-
is generally used as a range inside []
(A-z
) except when it is placed at the end where it just means the minus sign.
Probably a better explainer:
https://regex101.com/r/OYRnMO/1
Upvotes: 1