In JavaScript
how to make a input text contain only one letter maj and three Numbers
1/10/2017 6:06:25 PM
Garrach_hazem
50 Answers
New Answer<!DOCTYPE html> <html> <head> <title>Validation</title> <script> function validate(){ try { if (document.getElementsByTagName("input")[0].value.toString().match(/\d/g).length==3&&document.getElementsByTagName("input")[0].value.length==4){alert("valid");}else{alert("invalid");} }catch(e){alert("invalid");} } </script> </head> <body> <input type="text" oninput="validate();" placeholder="1 char & 3 nums"> </body> </html>
@visph I just gave him an example hoping he'll replace the "alert" with something else…… ~_~
You need to dynamicly handle it by yourself, with the help of javascript... Attach a 'onchange' event function to the input text you want the function control entry user in real-time. Inside this function, define the code to verify / correct the actual 'value" attribut content. Many kind of implementations are possible ;) [ EDIT ] 'onkeypress" event is preferable: check next post for code example and further explanations...
HTML: <input type="text" onkeypress="inputHandler(this, filter, correct);"> [ EDIT ] 'oninput' event is more useful in this case ( check next posts ) JS: function inputHandler(src, filterCallback, fixCallback) { if ( ! filterCallback(src.value) ) src.value=correct(src.value); } function filter(val) { /* code for return true if 'val' is valid, else return false */ } function correct(val) { /* code for return corrected value of 'val': simply need to retrieve invalid char */ } Not tested ( means verified this one ), but it's the idea for a generic parametric handler ( you can define and apply how many filter you want ). I change 'onchange' event by replacing it with 'onkeypress" because from memory, it's less problematic ( onchange is only called when entry is validate by the user, meaning when element lost focus, on keypress occurs each time user press a key, so each time the value is supposed to have changed )
'oninput' is clearly the better choice, because it's design especially for <input> element ( new event in html5 ). It's first difference/adavantage with keypress/keydown/keyup ( verified just now ) is that it will be fired in case of change due to a paste, or a drop, while key-family event don't ;)
I wrote simple example, check it in my codes. "Code for Garrrach_hazem". Try to input letters and numbers I can comment it later because i need to go now.