ब्लॉग

React Native में Next Level Form Handling

28 जून 2023 10 मिनट पढ़ने का समय

React Native में advanced form handling की तकनीकें। Validation, performance optimization और reusable form components बनाने के बारे में जानें।

React Native में Next Level Form Handling
React Nativeफॉर्म्सवैलिडेशनपरफॉर्मेंसReact Hook FormZod

React Native में Next Level Form Handling

Zod और React Hook Form से React Native में Form Handling को बेहतर बनाएँ

जिस भी application में user input चाहिए, वहाँ form handling एक बुनियादी हिस्सा है, और सही tools और libraries के साथ यह एक आसान और smooth प्रक्रिया बन सकती है। यह article आपको बताएगा कि react-hook-form और zod का इस्तेमाल करके react-native app में forms कैसे handle करें। इन दोनों को मिलाकर हम एक efficient form handling mechanism बनाएँगे। इसे समझाने के लिए एक basic signup form बनाते हैं।

पूरा source code article के आख़िर में दिया जाएगा।

Zod से Schema Declaration

शुरुआत में हम zod से अपना schema declare करते हैं। यह schema हमारे form data का अपेक्षित shape तय करेगा और हर field के लिए validations set करेगा। इन rules को define करने के लिए Zod कई powerful validation functions देता है।

यह रहा पूरा zod schema:

यह article मानकर चलता है कि आप zod की basics जानते हैं।

import z from "zod";

const phoneNumberRegexp = new RegExp(
  /^[\+]?([0-9][\s]?|[0-9]?)([(][0-9]{3}[)][\s]?|[0-9]{3}[-\s\.]?)[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
);
const FIELD_REQUIRED_STR = "This field is required";
export const GENDER_OPTIONS = ["Male", "Female", "Other"] as const;

export const signUpFormSchema = z.object({
  name: z
    .string({
      invalid_type_error: "Name must be a string",
      required_error: FIELD_REQUIRED_STR,
    })
    .min(3, "Minimum 3 characters")
    .max(20, "Maximum 20 characters")
    .trim(),

  surname: z
    .string({
      invalid_type_error: "Surname must be a string",
      required_error: FIELD_REQUIRED_STR,
    })
    .min(3, "Minimum 3 characters")
    .max(20, "Maximum 20 characters")
    .trim(),

  phoneNumber: z
    .string({
      invalid_type_error: "Phone number must be a number",
      required_error: FIELD_REQUIRED_STR,
    })
    .regex(phoneNumberRegexp, "Invalid phone number"),

  email: z
    .string({
      invalid_type_error: "Email must be a string",
      required_error: FIELD_REQUIRED_STR,
    })
    .email("Email is invalid"),

  gender: z.enum(GENDER_OPTIONS, {
    required_error: FIELD_REQUIRED_STR,
    invalid_type_error: `Invalid gender, must be one of the followings: ${GENDER_OPTIONS.join(
      ", "
    )}`,
  }),

  birthDate: z
    .date({
      invalid_type_error: "Birth date must be a date",
      required_error: FIELD_REQUIRED_STR,
    })
    .min(new Date("1900-01-01"), "Invalid date time, too old")
    .max(new Date("2023-01-01"), "Invalid date time, too young")
    .default(new Date()),
});

export type SignUpFormSchema = z.infer<typeof signUpFormSchema>;

इस schema में हम zod से बताते हैं कि हर field में क्या होना चाहिए। उदाहरण के लिए, name और surname fields 3 से 20 characters लंबी strings होनी चाहिए, जबकि phoneNumber field एक number होनी चाहिए।

कुछ fields के लिए हमारे पास ज़्यादा complex rules भी हैं। जैसे email field एक string होनी चाहिए और उसमें सिर्फ़ valid email addresses ही चलेंगे। gender field पहले से तय gender options ('Male', 'Female', या 'Other') में से एक होनी चाहिए।

आख़िर में, birthDate field date type की है और यह 1900-01-01 और 2023-01-01 के बीच की एक valid date होनी चाहिए। अगर कोई date न दी जाए, तो default रूप से यह मौजूदा date लेती है।

zod के साथ हम complex validation rules आसानी से बना सकते हैं। इस तरह हमारे form से मिलने वाला data गारंटी से वैसा ही होगा जैसा हम चाहते हैं।

अगला कदम schema type को infer करना है। Zod एक infer method देता है, जो किसी दिए गए zod schema का TypeScript type निकालता है।

export type SignUpFormSchema = z.infer<typeof signUpFormSchema>;

यह inferred type बाद में useForm में इस्तेमाल होता है ताकि हमारा form data हमारे schema से मेल खाए।

React Hook Form से Form Setup

इसके बाद हम 'react-hook-form' के useForm hook से अपना form set up करते हैं। यह hook form validation resolve करने के लिए हमारे zod schema को (zodResolver के ज़रिए) argument के रूप में लेता है।

const methods = useForm<SignUpFormSchema>({
  resolver: zodResolver(signUpFormSchema),
  defaultValues: {
    birthDate: new Date(),
  },
  mode: "onBlur",
});

resolver में हम अपना schema pass करते हैं। defaultValues property से हम form fields के लिए default values दे सकते हैं। इस case में हम default birthDate को मौजूदा date पर set कर रहे हैं। mode property तय करती है कि validation कब होगा। इस case में validation onBlur पर होगा, यानी जब user किसी field से हटेगा।

Field Rendering और Validation

हर form field को manage करने के लिए हम react-hook-form का Controller component इस्तेमाल करते हैं। यह हमें field और fieldState props देता है, जिनसे हम अपनी field की value, error state और validation manage करते हैं।

उदाहरण के लिए, name field हम ऐसे set up करते हैं:

<Controller
  control={methods.control}
  name="name"
  render={({ field: { onChange, onBlur, value }, fieldState: { error } }) => {
    return (
      <TextInput
        label="Name"
        onBlur={onBlur}
        value={value}
        onChangeText={onChange}
        errorMessage={error?.message}
      />
    );
  }}
/>

हर prop यह काम करता है:

  • control: यहाँ आप useForm hook से मिला control prop pass करते हैं। Controller को form state के साथ काम करने के लिए यह ज़रूरी है।

  • name: यह form के अंदर input की value तक पहुँचने की key है। जब आप form values निकालते या set करते हैं, तो यही key इस्तेमाल होती है। यह सभी form fields में unique होनी चाहिए।

  • render: यह एक function है जो आपका input element लौटाता है। यह function field और fieldState props देता है।

  • field: इसमें onChange, onBlur और value props होते हैं। इन्हें सीधे आपके controlled component से जोड़ना चाहिए। इस case में onChange को TextInput के onChangeText से जोड़ा गया है, जो user का input पकड़कर उसे form state में store करेगा।

  • fieldState: इसमें error prop होता है, जो इस field के validation errors की जानकारी देता है।

render prop के अंदर TextInput को customize किया गया है। onBlur और onChangeText को field के संबंधित methods से जोड़ा गया है, और value prop को इस input की मौजूदा form value से link किया गया है। validation fail होने पर errorMessage prop error message से जुड़ जाता है।

तो form submission या real-time validation के समय, अगर ‘name’ field Zod schema में तय validation requirements पूरी नहीं करती, तो error message इसी TextInput field में दिखेगा।

React Hook Form से Custom Validation Trigger करना

birthDate field के साथ एक अलग स्थिति बनती है, क्योंकि यह एक date picker component (इस case में RNDateTimePicker) इस्तेमाल करती है। यहाँ validation process को ख़ास तरीके से संभालना पड़ता है, क्योंकि date picker के साथ user का interaction आम text inputs से अलग होता है।

<Controller
  control={methods.control}
  name="birthDate"
  render={({ field: { onChange, onBlur, value }, fieldState: { error } }) => {
    return (
      <View>
        <Text>Birth date</Text>
        <RNDateTimePicker
          value={value}
          mode="date"
          onChange={(e) => {
            if (e.type === "set" && e.nativeEvent.timestamp) {
              onChange(new Date(e.nativeEvent.timestamp));
              methods.trigger("birthDate");
            }
          }}
        />
        {!!error?.message && <Text>{error.message}</Text>}
      </View>
    );
  }}
/>

जब user कोई date चुनता है, तो onChange event trigger होता है। इस event handler के अंदर हम पहले check करते हैं कि event type 'set' है या नहीं, जो बताता है कि user ने date set की है। फिर हम check करते हैं कि timestamp मौजूद है, ताकि पक्का हो कि date चुनी गई है।

इन conditions की पुष्टि होने पर हम new Date(e.nativeEvent.timestamp) से timestamp को JavaScript Date object में बदलते हैं। फिर यह नई value onChange को pass की जाती है, जो form में birthDate field की value update करता है।

लेकिन आम text inputs, जो बदलाव पर अपने आप validation trigger करते हैं, उनके उलट date pickers इस तरह validation trigger नहीं करते। इसलिए value update होने के बाद हमें validation को manually trigger करना पड़ता है। यह हम methods.trigger('birthDate') call करके करते हैं।

react-hook-form का दिया हुआ यह trigger method किसी खास field के लिए validation शुरू करता है। यहाँ date set होते ही यह birthDate field का validation trigger करता है, ताकि हमारे validation rules तुरंत लागू हों।

आख़िर में, अगर कोई validation errors हैं, तो वे {!!error?.message && {error.message}} के ज़रिए दिखेंगे, जहाँ error?.message में हमारे zod schema में तय validation error message होता है।

Form Submission: React Hook Form

React-hook-form package form submissions और error handling के लिए efficient methods देता है।

const onSubmit: SubmitHandler<SignUpFormSchema> = (data) => {
  console.log(JSON.stringify(data));
};

const onError: SubmitErrorHandler<SignUpFormSchema> = (errors, e) => {
  console.log(JSON.stringify(errors));
};

<Button
  onPress={methods.handleSubmit(onSubmit, onError)}
  title="Submit Form"
  color={"#007BFF"}
/>;

चलिए process को समझते हैं:

onSubmit handler form data को argument के रूप में पाता है। इस उदाहरण में हम बस इस data को log कर रहे हैं, लेकिन असली applications में इसे server पर भेजा जा सकता है या application की ज़रूरत के हिसाब से आगे process किया जा सकता है।

वहीं onError function तब call होता है जब form submission पर validation errors हों। errors object में उन सभी fields की विस्तृत जानकारी होती है जिनका validation fail हुआ। इस उदाहरण में हम बस इन errors को log कर रहे हैं।

अगर हर field में error हो, तो error object ऐसा होगा:

    {
      "name": {
        "message": "This field is required",
        "type": "invalid_type",
        "ref": {
          "name": "name"
        }
      },
      "surname": {
        "message": "This field is required",
        "type": "invalid_type",
        "ref": {
          "name": "surname"
        }
      },
      "phoneNumber": {
        "message": "This field is required",
        "type": "invalid_type",
        "ref": {
          "name": "phoneNumber"
        }
      },
      "email": {
        "message": "This field is required",
        "type": "invalid_type",
        "ref": {
          "name": "email"
        }
      },
      "gender": {
        "message": "This field is required",
        "type": "invalid_type",
        "ref": {
          "name": "gender"
        }
      },
      "birthDate": {
        "message": "Invalid date time, too young",
        "type": "too_big",
        "ref": {
          "name": "birthDate"
        }
      }
    }

Zod से Pre-validation

नीचे दिया code block form submission event से पहले Zod के safeParse method से form data को manually pre-validate करने का तरीका दिखाता है। हालाँकि form validation पहले से React Hook Form के handleSubmit method से हो रहा है, फिर भी pre-validation developers को form validation process पर ज़्यादा नियंत्रण दे सकता है।

<Button
  title="Submit Form"
  onPress={() => {
    // get current form values
    const currFormValues = methods.getValues();

    // Prevalidate using zod's safeParse
    const result = signUpFormSchema.safeParse(currFormValues);

    // If prevalidation is failed, display the error
    if (!result.success) {
      Alert.alert(JSON.stringify(result.error));
    } else {
      // If prevalidation is successful, notify the user
      Alert.alert("Validation is successful with zod");
    }
  }}
/>

ऊपर के code का विश्लेषण करते हैं:

  • Button के onPress event से एक function चलाया जा रहा है जो form submission से पहले pre-validation करता है।

  • मौजूदा form values निकालने के लिए methods (जो React Hook Form देता है) का getValues method इस्तेमाल होता है।

  • फिर ये values signUpFormSchema (शुरुआत में बनाया गया zod schema) के safeParse method को pass की जाती हैं। zod pre-validation इसी कदम पर होता है। zod के parse method के उलट, safeParse validation fail होने पर error throw नहीं करता। इसके बजाय यह एक object लौटाता है जिसमें success boolean होता है और, अगर validation fail हुआ हो, तो एक error object।

  • एक conditional statement check करता है कि result.success false है या नहीं (यानी validation fail हुआ)। अगर false है, तो यह validation error दिखाने वाला alert trigger करता है।

  • अगर result.success true है (यानी validation सफल रहा), तो यह alert trigger करता है कि zod से validation सफल रहा।

भले ही यह तरीका दोहराव जैसा लगे, क्योंकि React Hook Form का handleSubmit पहले से zod से दिए गए schema के साथ form validation करता है, फिर भी कुछ खास स्थितियों में यह फ़ायदेमंद हो सकता है। जैसे आप कुछ actions सिर्फ़ manual validation के बाद करना चाहें, या user के form भरते समय real-time में inputs validate करना चाहें। ऐसे cases में zod के safeParse method से pre-validation काफ़ी काम का हो सकता है।

और zod error object कुछ ऐसा दिखेगा:

    {
      "issues": [
        {
          "code": "invalid_type",
          "expected": "string",
          "received": "undefined",
          "path": [
            "name"
          ],
          "message": "This field is required"
        },
        {
          "code": "invalid_type",
          "expected": "string",
          "received": "undefined",
          "path": [
            "surname"
          ],
          "message": "This field is required"
        },
        {
          "code": "invalid_type",
          "expected": "string",
          "received": "undefined",
          "path": [
            "phoneNumber"
          ],
          "message": "This field is required"
        },
        {
          "code": "invalid_type",
          "expected": "string",
          "received": "undefined",
          "path": [
            "email"
          ],
          "message": "This field is required"
        },
        {
          "expected": "'Male' | 'Female' | 'Other'",
          "received": "undefined",
          "code": "invalid_type",
          "path": [
            "gender"
          ],
          "message": "This field is required"
        },
        {
          "code": "too_big",
          "message": "Invalid date time, too young",
          "inclusive": true,
          "exact": false,
          "maximum": 1672531200000,
          "type": "date",
          "path": [
            "birthDate"
          ]
        }
      ],
      "name": "ZodError"
    }

यह वाकई एक बड़ा object है, और इसमें हमारे case के लिए कुछ गैर-ज़रूरी fields भी हो सकती हैं। अच्छी बात है कि zod errors को format करने का एक method देता है।

हम बस result.error.format() इस्तेमाल कर सकते हैं और बाकी काम zod अंदर ही संभाल लेगा।

if (!result.success) {
  // Format errors using result.error.format()
  const formattedError = result.error.format();
  Alert.alert(JSON.stringify(formattedError));
} else {
  Alert.alert("Validation is successful with zod");
}

Formatted error object ऐसा दिखेगा:

    {
      "name": {
        "_errors": [
          "This field is required"
        ]
      },
      "surname": {
        "_errors": [
          "This field is required"
        ]
      },
      "phoneNumber": {
        "_errors": [
          "This field is required"
        ]
      },
      "email": {
        "_errors": [
          "This field is required"
        ]
      },
      "gender": {
        "_errors": [
          "This field is required"
        ]
      },
      "birthDate": {
        "_errors": [
          "Invalid date time, too young"
        ]
      }
    }

नवीनतम code

नीचे सबसे नया code है (imports और styles को छोड़कर)। अगर आप पूरा source code देखना चाहते हैं, तो article के आख़िर में देखें।

// imports...

export const SignupForm: React.FC = () => {
  const [shouldValidateWithZod, setShouldValidateWithZod] =
    React.useState<boolean>(false);

  const [isCalendarOpenForAndroid, setIsCalendarOpenForAndroid] =
    React.useState<boolean>(false);

  const methods = useForm<SignUpFormSchema>({
    resolver: zodResolver(signUpFormSchema),
    defaultValues: {
      birthDate: new Date(),
    },
    mode: "onBlur",
  });

  const onSubmit: SubmitHandler<SignUpFormSchema> = (data) => {
    console.log(JSON.stringify(data));
  };

  const onError: SubmitErrorHandler<SignUpFormSchema> = (errors, e) => {
    console.log(JSON.stringify(errors));
    Alert.alert("Warning", getReadableValidationErrorMessage(errors));
  };

  return (
    <SafeAreaView edges={["top", "bottom"]} style={styles.safeArea}>
      <ScrollView>
        <Text style={styles.title}>Sign Up Form</Text>
        <View style={styles.root}>
          <FormProvider {...methods}>
            <Controller
              control={methods.control}
              name="name"
              render={({
                field: { onChange, onBlur, value },
                fieldState: { error },
              }) => {
                return (
                  <TextInput
                    label="Name"
                    onBlur={onBlur}
                    value={value}
                    onChangeText={onChange}
                    errorMessage={error?.message}
                  />
                );
              }}
            />
            <View style={styles.spacing} />
            <Controller
              control={methods.control}
              name="surname"
              render={({
                field: { onChange, onBlur, value },
                fieldState: { error },
              }) => {
                return (
                  <TextInput
                    label="Surname"
                    onBlur={onBlur}
                    value={value}
                    onChangeText={onChange}
                    errorMessage={error?.message}
                  />
                );
              }}
            />
            <View style={styles.spacing} />

            <Controller
              control={methods.control}
              name="email"
              render={({
                field: { onChange, onBlur, value },
                fieldState: { error },
              }) => {
                return (
                  <TextInput
                    label="Email"
                    onBlur={onBlur}
                    value={value}
                    onChangeText={onChange}
                    errorMessage={error?.message}
                  />
                );
              }}
            />

            <View style={styles.spacing} />

            <Controller
              control={methods.control}
              name="phoneNumber"
              render={({
                field: { onChange, onBlur, value },
                fieldState: { error },
              }) => {
                return (
                  <TextInput
                    label="Phone number"
                    onBlur={onBlur}
                    keyboardType="decimal-pad"
                    value={value}
                    onChangeText={(val) => onChange(val.toString())}
                    errorMessage={error?.message}
                  />
                );
              }}
            />

            <View style={styles.spacing} />

            <Controller
              control={methods.control}
              name="birthDate"
              render={({
                field: { onChange, value },
                fieldState: { error },
              }) => {
                return (
                  <View style={styles.dateWrapper}>
                    <Text style={styles.label}>Birth date</Text>

                    {Platform.OS === "android" && (
                      <Button
                        onPress={() => {
                          setIsCalendarOpenForAndroid(true);
                        }}
                        title={value.toString()}
                      />
                    )}

                    {(isCalendarOpenForAndroid ||
                      Platform.OS !== "android") && (
                      <RNDateTimePicker
                        value={value}
                        style={styles.dateTimePicker}
                        mode={"date"}
                        onChange={(e) => {
                          if (Platform.OS === "android") {
                            setIsCalendarOpenForAndroid(false);
                          }

                          if (e.type === "set" && e.nativeEvent.timestamp) {
                            onChange(new Date(e.nativeEvent.timestamp));
                            methods.trigger("birthDate");
                          }
                        }}
                      />
                    )}

                    {!!error?.message && (
                      <Text style={styles.errorMessageText}>
                        {error.message}
                      </Text>
                    )}
                  </View>
                );
              }}
            />

            <View style={styles.spacing} />

            <Controller
              control={methods.control}
              name="gender"
              render={({
                field: { onChange, onBlur, value, ref },
                fieldState: { error },
              }) => {
                return (
                  <View style={styles.genderWrapper}>
                    <Text style={styles.label}>Gender</Text>
                    <View style={styles.genderOptionsWrapper}>
                      {GENDER_OPTIONS.map((genderOption) => (
                        <Pressable
                          key={genderOption}
                          style={[
                            styles.genderOptionPressable,
                            {
                              backgroundColor:
                                value === genderOption ? "#007BFF" : "#F2F2F2",
                            },
                          ]}
                          onPress={() => onChange(genderOption)}
                        >
                          <Text
                            style={[
                              styles.genderOptionText,
                              {
                                color: value === genderOption ? "#fff" : "#000",
                              },
                            ]}
                          >
                            {genderOption}
                          </Text>
                        </Pressable>
                      ))}
                    </View>
                    {!!error?.message && (
                      <Text style={styles.errorMessageText}>
                        {error.message}
                      </Text>
                    )}
                  </View>
                );
              }}
            />

            <View style={styles.spacing} />

            <Text style={styles.label}>Should validate with zod</Text>

            <Switch
              value={shouldValidateWithZod}
              onChange={(e) => setShouldValidateWithZod(e.nativeEvent.value)}
            />
            <View style={styles.spacing} />

            <Button
              onPress={
                shouldValidateWithZod
                  ? () => {
                      /** we could also prevalidate using zod like below */

                      // get current form values
                      const currFormValues = methods.getValues();
                      // https://zod.dev/?id=safeparse
                      const result = signUpFormSchema.safeParse(currFormValues);

                      if (!result.success) {
                        const formattedError = result.error.format();
                        Alert.alert(JSON.stringify(formattedError));
                      } else {
                        Alert.alert("Validation is successful with zod");
                      }
                    }
                  : methods.handleSubmit(onSubmit, onError)
              }
              title="Submit Form"
              color={"#007BFF"}
            />
          </FormProvider>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

// styles...

यह sample app expo go से लिखा गया है। यानी आप नीचे दिए QR code से इसे आसानी से test कर सकते हैं! (अगर QR काम न करे, तो article के आख़िर में दिया source code link देखें।)

निष्कर्ष

इस article में हमने देखा कि React Native application में मज़बूत form validation बनाने के लिए React Hook Form, Zod और TypeScript के combination का असरदार इस्तेमाल कैसे करें। हमने देखा कि इन libraries की flexibility और ताकत से हम साफ़, type-safe code लिख सकते हैं जो complex validation requirements संभाल सके।

React Hook Form और Zod का तालमेल हमें दोनों का फ़ायदा देता है। React Hook Form form handling को आसान बनाता है, re-rendering को optimize करता है, और इसमें form state management और error handling जैसे features हैं। दूसरी तरफ़ Zod सुरक्षा की एक अतिरिक्त परत देता है, जिससे हम तय कर सकते हैं कि हर form field में किस तरह का data allowed है और इन rules को लागू कर सकते हैं।

याद रखें, यहाँ दिखाई गई techniques भले ही एक simple SignUp form के संदर्भ में इस्तेमाल हुई हैं, लेकिन ये आपकी React Native applications के किसी भी form-based user input पर लागू होती हैं। इन strategies को अपनाकर आप पक्का कर सकते हैं कि आपके forms user-friendly, मज़बूत और maintainable हों, जिससे बेहतर user experience और ज़्यादा मज़बूत applications बनें।

पूरे source code का link