HTML5 input pattern for French licence plate number - html

I'm searching for a html pattern to check an input field containing a licence plate number.
Problem is we have many possible patterns :
AA-123-ZZ
1234-AZ-09
123-ABC-90
Can you help me write such a pattern ?
Cherry on the cake would be if the user can write the - or not.
Thank's

This should cover the three input options as specified:
<form action="carCheck.asp" method="post">
Number Plate: <input type="text" name="number plate" pattern="^([A-Za-z]{2}-?[0-9]{3}-?[A-Za-z]{2})?([0-9]{4}-?[A-Za-z]{2}-?[0-9]{2})?([0-9]{3}-?[A-Za-z]{3}-?[0-9]{2})?$" title="French Number Plate">
<input type="submit">
</form>
Edit: also worth considering is restricted/unused characters in French Number plates (I,O,U)...
pattern="^((?![IOUiou])[A-Za-z]{2}-?[0-9]{3}-?(?![IOUiou])[A-Za-z]{2})?([0-9]{4}-?(?![IOUiou])[A-Za-z]{2}-?[0-9]{2})?([0-9]{3}-?(?![IOUiou])[A-Za-z]{3}-?[0-9]{2})?$"
EDIT: 2nd pattern above to allow lowercase alpha as well as uppercase.
This should cover:
Aa-999-Aa and Aa999Aa
9999-Aa-99 and 9999Aa99
999-AaA-99 and 999AaA99

How about:
pattern="^[A-Z0-9]{1,4}-?[A-Z0-9]{1,4}-?[A-Z0-9]{1,4}$"
3 groups of A-Z/0-9 (1 to 4 symbols), separated by (maybe missing) hypens.
Edit: if you want each group to contain only letters or only numbers, pattern will be the following:
pattern="^([A-Z]{1,4}|[0-9]{1,4})-?([A-Z]{1,4}|[0-9]{1,4})-?([A-Z]{1,4}|[0-9]{1,4})$"
Also, Paul McCombie's answer below contains an amendment on characters unused in license plates, you may want to look at it too.
Update:
pattern="^([A-HJ-NP-TV-Z]{2}|[0-9]{3,4})-?([A-HJ-NP-TV-Z]{2,3}|[0-9]{3})-?([A-HJ-NP-TV-Z]{2}|[0-9]{2})$"

There are 2 solution for your problem That need Regex:
HTML5 input pattern.
Using javaScript to validate input with regex.Test now
HTML5 input pattern
The pattern attribute specifies a regular expression that the element's value is checked against.
<input type="text" name="licence" pattern="(\w+-\w+-\w+)"title="Your input">
Javascript Regex
var re = /(\w+-\w+-\w+)/;
var str = '123-ABC-90';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

Related

How to create input text patterns (html forms)

I have tried to create an input text pattern that only allows 8 digits and a capital or simple "d" at the end of it but I can't seem to limit the number of digits. example 12345678d or 12345678D
<input type="text" name="studentid" placeholder="Student ID"
pattern="[0-9]+[dD]" >
You can specify that there should be exactly 8 digits with pattern="[0-9]{8}[dD]".
The answer is very simple but I'm gonna explain why it's important to think and handle edge cases. If you aren't interested in that, go to the end of the code block and copy the regex pattern.
Let's start with the pattern you have tried:
var pattern = /\d+[dD]/
var txt1 = "123458D";
console.log(txt1.match(pattern));
That's a false positive, it should not have matched. the problem is that we have not specified that we need 8 digits, so let's fix that.
var pattern = /\d{8}[dD]{1}/
var txt1 = "123458D";
console.log(txt1.match(pattern)); //Doesn't match, so Good now
//But, We are not done yet
var txt2 = "123456789D"
console.log(txt2.match(pattern)); //["23456789D"] Might be a problem
We have run into another problem, let's fix that by making sure that we get only 8 digits starting from the beginning.
var pattern = /^\d{8}[dD]{1}/
var txt3 = "123456789D"
console.log(txt3.match(pattern)); //Doesn't match, so Good now
var txt4 = "12345678Dblah blah 2312412"
console.log(txt4.match(pattern)); //["12345678D"] Might be a problem
Arrgghh! We are still not done. Let's put that last one fix and make sure that we end with a "D" or "d".
var txt4 = "12345678Dblah blah 2312412"
var pattern = /^\d{8}[dD]{1}$/
console.log(txt4.match(pattern)); //Doesn't match now, We are good
The maxlength attribute is used to set a limit of maximum character one can enter in the textbox.
<input type="text" maxlength="9" pattern ="[0-9]{8}[dD]">

HTML input pattern for alphanumeric, underscore, dash and dot

I wanted to form pattern in HTML input field, which can have only below allowed chars:
alfanumeric (a-zA-Z0-9)
underscore (_)
dash (-)
dot (.)
I am trying pattern="[a-zA-Z0-9_-\.]" but it is not working. Not sure why. How I can do it?
Some valid example input:
aA12_-.
Aasdj
123123
_Afsdf.
_end.1
Your pattern matches only a single character. If you want to match multiple characters including zero append *, for at least one character append + e.g.
<input pattern="[-a-zA-Z0-9_\.]+" />
read more at https://www.w3schools.com/tags/att_input_pattern.asp
Try this:
/^[\w\._-]+$/
Note:
1) Use - at the end of the bracket.
2) You are not allowed to use the space Between words.(if you want space between words insert space inside bracket like this : /^[\w\._ -]+$/)
patt = /^[\w\._-]+$/;
function test(){
var v = document.getElementById('txt').value;
v = v.trim();
console.log(patt.test(v));
}
<input type="text" id="txt">
<button onclick="test()">test</button>

How to write regex expression for this type of text?

I'm trying to extract the price from the following HTML.
<td>$75.00/<span class='small font-weight-bold text-
danger'>Piece</span></small> *some more text here* </td>
What is the regex expression to get the number 75.00?
Is it something like:
<td>$*/<span class='small font-weight-bold text-danger'>
The dollar sign is a special character in regex, so you need to escape it with a backslash. Also, you only want to capture digits, so you should use character classes.
<td>\$(\d+[.]\d\d)<span
As the other respondent mentioned, regex changes a bit with each implementing language, so you may have to make some adjustments, but this should get you started.
I think you can go with /[0-9]+\.[0-9]+/.
[0-9] matches a single number. In this example you should get the number 7.
The + afterwards just says that it should look for more then just one number. So [0-9]+ will match with 75. It stops there because the character after 5 is a period.
Said so we will add a period to the regex and make sure it's escaped. A period usually means "every character". By escaping it will just look for a period. So we have /[0-9]+\./ so far.
Next we just to add [0-9]+ so it will find the other number(s) too.
It's important that you don't give it the global-flag like this /[0-9]+\.[0-9]+/g. Unless you want it to find more then just the first number/period-combination.
There is another regex you can use. It uses the parentheses to group the part you're looking for like this: /<td>\$(.+)<span/
It will match everything from <td>$ up to <span. From there you can filter out the group/part you're looking for. See the examples below.
// JavaScript
const text = "<td>$something<span class='small font-weight..."
const regex = /<td>\$(.+)<span/g
const match = regex.exec(text) // this will return an Array
console.log( match[1] ) // prints out "something"
// python
text = "<td>$something<span class='small font-weight..."
regex = re.compile(r"<td>\$(.+)<span")
print( regex.search(text).group(1) ) // prints out "something"
As an alternative you could use a DOMParser.
Wrap your <td> inside a table, use for example querySelector to get your element and get the first node from the childNodes.
That would give you $75.00/.
To remove the $ and the trailing forward slash you could use slice or use a regex like \$(\d+\.\d+) and get the value from capture group 1.
let html = `<table><tr><td>$75.00/<span class='small font-weight-bold text-
danger'>Piece</span></small> *some more text here* </td></tr></table>`;
let parser = new DOMParser();
let doc = parser.parseFromString(html, "text/html");
let result = doc.querySelector("td");
let textContent = result.childNodes.item(0).nodeValue;
console.log(textContent.slice(1, -1));
console.log(textContent.match(/\$(\d+\.\d+)/)[1]);

How to create an input field (HTML) that spans two lines

I want to be able to use an <input> field type of control but allow only two lines.
At the moment I am using two fields but was wondering if anyone can come up with a solution to allow input (similar to a textarea) but no more than two lines. I control the width etc of the field.
For reference, Jquery and Bootstrap 3 are loaded.
Any help much appreciated.
try this
var element = document.getElementById('tworows');
make2Lines(element);
function make2Lines(el){
el.setAttribute('rows', 2); // limit height to 2 rows
// el.setAttribute('wrap', 'off'); // ensure no softwrap is not required anymore if we limit the length
el.addEventListener('keydown', limit); // add listener everytime a key is pressed
function limit(e){
if(e.keyCode == 13 && this.value.indexOf('\n')>-1){
// 13 is the ENTER key and \n is the value it make in the textarea
// so if we already have a line break and it's the ENTER key, we prevent it
e.preventDefault();
}
// async to let the dom update before changin the value
setTimeout(limitRow.bind(this), 0);
}
function limitRow(){
var maxLength = 10;
var rows = this.value.split('\n');
rows.forEach(cutOverflow)
this.value = rows.join('\n');
function cutOverflow(row, index, rows) {
rows[index] = row.substring(0, maxLength);
// this if is only if you want to automatically jump to the next line
if (index === 0 && row.length > maxLength)
rows[1] = row.substring(maxLength) + (rows[1] || '');
}
}
}
<textarea id="tworows"></textarea>
short version : function make2Lines(a){function b(a){13==a.keyCode&&this.value.indexOf("\n")>-1&&a.preventDefault(),setTimeout(c.bind(this),0)}function c(){function c(b,c,d){d[c]=b.substring(0,a),0===c&&b.length>a&&(d[1]=b.substring(a)+(d[1]||""))}var a=10,b=this.value.split("\n");b.forEach(c),this.value=b.join("\n")}a.setAttribute("rows",2),a.addEventListener("keydown",b)}
Two ways come to mind:
You could use a <textarea> instead, and augment it with some script that only allows two lines.
You could continue to use two <input> fields, but style them so they stack on top of each other to create the illusion of one field. You might still need a bit of script to take care of some usability annoyances, such as pressing ENTER to go from line one to line two.
If you are talking about wrapping lines if the text is too long, according to documentation <input type="text"> cannot wrap text.
However, if you are talking about limiting the character length, you could use the maxlength attribute like- <input type="text" maxlength="10">
An input field can only display one line http://www.w3.org/TR/html-markup/input.text.html#input.text. For multiline you need to use textarea and set the rows attribute. If you need two separate values you can do it after in PHP, Javascript or other means.
<textarea class="form-control" rows="2">The default text or empty for nothing this is passed as value for this field</textarea>

AS3 validate form fields?

I wrote a AS3 script, i have 2 fields to validate, i.e email and name.
For email i use:
function isValidEmail(Email:String):Boolean {
var emailExpression:RegExp = /^[a-z][\w.-]+#\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
return emailExpression.test(Email);
}
How about name field? Can you show me some sample code?
EDIT:
Invalid are:
blank
between 4 - 20 characters
Alphanumeric only(special characters not allowed)
Must start with alphabet
I think you probably want a function like this:
function isNameValid(firstname:String):Boolean
{
var nameEx:RegExp = /^([a-zA-Z])([ \u00c0-\u01ffa-zA-Z']){4,20}+$/;
return nameEx.test(firstname);
}
Rundown of that regular expression:
[a-zA-Z] - Checks if first char is a normal letter.
[ \u00c0-\u01ffa-zA-Z'] - Checks if all other chars are unicode characters or a space. So names like "Mc'Neelan" will work.
{4,20} - Makes sure the name is between 4 and 20 chars in length.
You can remove the space at the start of the middle part if you don't want spaces.
Hope this helps. here are my references:
Regular expression validate name asp.net using RegularExpressionValidator
Java - Regular Expressions: Validate Name
function isNameValid(firstname:String):Boolean
{
var nameEx:RegExp = /^([a-zA-Z])([ \u00c0-\u01ffa-zA-Z']){4,20}+$/;
return nameEx.test(firstname);
}
{4,20} instead {2,20}
Problem avoided for names like Ajit