Created
September 25, 2020 23:58
-
-
Save nikola-wd/0b18148c6bbd8723143bc60f9a0f8aa9 to your computer and use it in GitHub Desktop.
[Validation - allow only numbers onKeyPress] #javascript #validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {event} evt = e (from the element) | |
* @param {bool} isZIP=false | |
* @returns {bool} | |
*/ | |
const validateNumberHelper = (evt, isZIP = false) => { | |
var theEvent = evt || window.event; | |
// Handle paste | |
if (theEvent.type === "paste") { | |
// event is deprecated | |
// key = event.clipboardData.getData("text/plain"); | |
} else { | |
// Handle key press | |
var key = theEvent.keyCode || theEvent.which; | |
key = String.fromCharCode(key); | |
} | |
const preventTyping = () => { | |
theEvent.returnValue = false; | |
if (theEvent.preventDefault) theEvent.preventDefault(); | |
} | |
var regex = /[0-9]|\./; | |
if (isZIP) { | |
if (evt.target.value.length > 4) { | |
preventTyping(); | |
} | |
} | |
if (!regex.test(key)) { | |
preventTyping(); | |
} | |
}; | |
export default validateNumberHelper; | |
// __________________________________________________________ | |
let component = ( | |
<input | |
className="input" | |
type={type} | |
placeholder={placeholder} | |
id={id} | |
name={id} | |
value={fieldValue} | |
onChange={handleChange} | |
onPaste={ | |
(e) => { | |
if (id === "patient_zip" || id === "patient_phone") { | |
e.preventDefault(); | |
} | |
} | |
} | |
onKeyPress={(e) => { | |
if (id === "patient_zip") { | |
validateNumberHelper(e, true); | |
} | |
if (id === "patient_phone") { | |
validateNumberHelper(e); | |
} else { | |
return false; | |
} | |
}} | |
onKeyUp={onKeyUp} | |
/> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment