UNPKG

@costilladante/password-validator

Version:

A customizable React password validator component with accessibility features

24 lines (23 loc) 10.7 kB
(function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.PasswordValidator={},f.React))})(this,function(f,p){"use strict";var Y={exports:{}},O={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var $;function ne(){if($)return O;$=1;var a=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function s(n,l,d){var w=null;if(d!==void 0&&(w=""+d),l.key!==void 0&&(w=""+l.key),"key"in l){d={};for(var m in l)m!=="key"&&(d[m]=l[m])}else d=l;return l=d.ref,{$$typeof:a,type:n,key:w,ref:l!==void 0?l:null,props:d}}return O.Fragment=r,O.jsx=s,O.jsxs=s,O}var N={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var J;function oe(){return J||(J=1,process.env.NODE_ENV!=="production"&&function(){function a(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===_e?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case g:return"Profiler";case v:return"StrictMode";case fe:return"Suspense";case pe:return"SuspenseList";case me:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case h:return"Portal";case M:return(e.displayName||"Context")+".Provider";case j:return(e._context.displayName||"Context")+".Consumer";case de:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ve:return t=e.displayName||null,t!==null?t:a(e.type)||"Memo";case V:t=e._payload,e=e._init;try{return a(e(t))}catch{}}return null}function r(e){return""+e}function s(e){try{r(e);var t=!1}catch{t=!0}if(t){t=console;var o=t.error,u=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return o.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",u),r(e)}}function n(e){if(e===k)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===V)return"<...>";try{var t=a(e);return t?"<"+t+">":"<...>"}catch{return"<...>"}}function l(){var e=L.A;return e===null?null:e.getOwner()}function d(){return Error("react-stack-top-frame")}function w(e){if(K.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function m(e,t){function o(){ee||(ee=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}o.isReactWarning=!0,Object.defineProperty(e,"key",{get:o,configurable:!0})}function T(){var e=a(this.type);return re[e]||(re[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function I(e,t,o,u,A,R,q,U){return o=R.ref,e={$$typeof:i,type:e,key:t,props:R,_owner:A},(o!==void 0?o:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:T}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:q}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function b(e,t,o,u,A,R,q,U){var c=t.children;if(c!==void 0)if(u)if(be(c)){for(u=0;u<c.length;u++)x(c[u]);Object.freeze&&Object.freeze(c)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else x(c);if(K.call(t,"key")){c=a(e);var y=Object.keys(t).filter(function(Re){return Re!=="key"});u=0<y.length?"{key: someKey, "+y.join(": ..., ")+": ...}":"{key: someKey}",ae[c+u]||(y=0<y.length?"{"+y.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,u,c,y,c),ae[c+u]=!0)}if(c=null,o!==void 0&&(s(o),c=""+o),w(t)&&(s(t.key),c=""+t.key),"key"in t){o={};for(var W in t)W!=="key"&&(o[W]=t[W])}else o=t;return c&&m(o,typeof e=="function"?e.displayName||e.name||"Unknown":e),I(e,c,R,A,l(),o,q,U)}function x(e){typeof e=="object"&&e!==null&&e.$$typeof===i&&e._store&&(e._store.validated=1)}var P=p,i=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),v=Symbol.for("react.strict_mode"),g=Symbol.for("react.profiler"),j=Symbol.for("react.consumer"),M=Symbol.for("react.context"),de=Symbol.for("react.forward_ref"),fe=Symbol.for("react.suspense"),pe=Symbol.for("react.suspense_list"),ve=Symbol.for("react.memo"),V=Symbol.for("react.lazy"),me=Symbol.for("react.activity"),_e=Symbol.for("react.client.reference"),L=P.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=Object.prototype.hasOwnProperty,be=Array.isArray,C=console.createTask?console.createTask:function(){return null};P={"react-stack-bottom-frame":function(e){return e()}};var ee,re={},te=P["react-stack-bottom-frame"].bind(P,d)(),se=C(n(d)),ae={};N.Fragment=k,N.jsx=function(e,t,o,u,A){var R=1e4>L.recentlyCreatedOwnerStacks++;return b(e,t,o,!1,u,A,R?Error("react-stack-top-frame"):te,R?C(n(e)):se)},N.jsxs=function(e,t,o,u,A){var R=1e4>L.recentlyCreatedOwnerStacks++;return b(e,t,o,!0,u,A,R?Error("react-stack-top-frame"):te,R?C(n(e)):se)}}()),N}var z;function le(){return z||(z=1,process.env.NODE_ENV==="production"?Y.exports=ne():Y.exports=oe()),Y.exports}var E=le();function G(a){var r,s,n="";if(typeof a=="string"||typeof a=="number")n+=a;else if(typeof a=="object")if(Array.isArray(a)){var l=a.length;for(r=0;r<l;r++)a[r]&&(s=G(a[r]))&&(n&&(n+=" "),n+=s)}else for(s in a)a[s]&&(n&&(n+=" "),n+=s);return n}function D(){for(var a,r,s=0,n="",l=arguments.length;s<l;s++)(a=arguments[s])&&(r=G(a))&&(n&&(n+=" "),n+=r);return n}const B={valid:"✅",invalid:"❌"};class X{constructor(r,s){this.name=r,this.message=s}}class F extends X{constructor(r,s,n){super(r,s),this.pattern=n}validate(r){return this.pattern.test(r)?null:this.message}}class H extends X{constructor(r,s,n){super(r,s),this.validator=n}validate(r){return this.validator(r)?null:this.message}}class Z{constructor(r){this.rules=r}validate(r){return this.rules.map(s=>s.validate(r)).filter(s=>s!==null)}}const ie=a=>!/(.)\1\1/.test(a),Q=new Z([new F("specialChar","Must include at least one special character (!@#$%^&*)",/[!@#$%^&*]/),new F("number","Must include at least one number",/[0-9]/),new F("uppercase","Must include at least one uppercase letter",/[A-Z]/),new H("noConsecutive","Must not have three or more consecutive identical characters",ie)]),ue=(a,r,s)=>{const[n,l]=p.useState(""),[d,w]=p.useState(!0),[m,T]=p.useState(a.rules.map(i=>({rule:i,isValid:!1}))),I=m.some(i=>!i.isValid);p.useEffect(()=>{r==null||r(!1,m),s==null||s("")},[]);const b=p.useCallback(i=>{if(i.length===0){const v=a.rules.map(g=>({rule:g,isValid:!1}));return T(v),r==null||r(!1,v),!1}const h=a.rules.map(v=>({rule:v,isValid:v.validate(i)===null}));T(h);const k=h.every(v=>v.isValid);return r==null||r(k,h),h.every(v=>v.isValid)},[a,r]),x=p.useCallback(i=>{l(i),b(i),s==null||s(i)},[b,s]),P=p.useCallback(()=>{w(i=>!i)},[]);return{inputValue:n,validationResults:m,changeInputChange:x,isPasswordVisible:d,hasInvalidRules:I,togglePasswordVisibility:P}},_={"password-validator-container":"_password-validator-container_1slrq_1","password-validator-input-wrapper":"_password-validator-input-wrapper_1slrq_8","password-validator-input":"_password-validator-input_1slrq_8","password-validator-toggle":"_password-validator-toggle_1slrq_27","password-validator-list":"_password-validator-list_1slrq_43","password-validator-list-item":"_password-validator-list-item_1slrq_49","password-validator-list-item-message":"_password-validator-list-item-message_1slrq_52","is-valid":"_is-valid_1slrq_56","is-invalid":"_is-invalid_1slrq_60"},S="password-validator",ce=({ruleSet:a=Q,showToggle:r=!0,indicators:s=B,onValidationChange:n,onValueChange:l,className:d,inputClassName:w,indicatorClassName:m})=>{const{inputValue:T,validationResults:I,isPasswordVisible:b,hasInvalidRules:x,changeInputChange:P,togglePasswordVisibility:i}=ue(a,n,l),h="password-input",k="password-validation-list";return E.jsxs("div",{className:D(_[`${S}-container`],d),role:"group",children:[E.jsxs("div",{className:_[`${S}-input-wrapper`],children:[E.jsx("input",{id:h,className:D(_[`${S}-input`],w),placeholder:"Enter Password",type:b?"text":"password",value:T,onChange:g=>P(g.target.value),tabIndex:0,"aria-label":"Enter Password","aria-describedby":T?k:void 0,"aria-invalid":x,"aria-required":"true"}),r&&E.jsx("button",{id:"password-toggle",type:"button",className:_[`${S}-toggle`],onClick:i,"aria-label":b?"Hide password":"Show password","aria-pressed":b,children:b?"👁️":"👁️‍🗨️"})]}),E.jsx("div",{id:"password-rules",className:_[`${S}-rules`],role:"region","aria-live":"polite","aria-relevant":"additions removals",children:T&&E.jsx("ul",{id:k,className:_[`${S}-list`],"aria-label":"Password requirements",children:I.map(({rule:g,isValid:j},M)=>E.jsxs("li",{id:`rule-${M}`,className:D(_["password-validator-list-item"],{[_["is-valid"]]:j,[_["is-invalid"]]:!j},m),"aria-label":`${j?"Valid":"Invalid"}`,children:[E.jsx("span",{"aria-hidden":"true",role:"img","aria-label":j?"Valid":"Invalid",children:j?s.valid:s.invalid}),E.jsx("span",{className:_[`${S}-list-item-message`],children:g.message})]},g.name))})})]})};f.DEFAULT_INDICATORS=B,f.FunctionRule=H,f.PasswordValidator=ce,f.RegExpRule=F,f.RuleSet=Z,f.defaultRules=Q,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=password-validator.umd.js.map